package com.forest.datachangetracker.service.audit.impl;

import cn.hutool.core.util.ObjectUtil;
import com.forest.datachangetracker.annotation.DataAudit;
import com.forest.datachangetracker.context.AuditContext;
import com.forest.datachangetracker.enums.OperationType;
import com.forest.datachangetracker.service.audit.AuditStrategy;
import lombok.extern.slf4j.Slf4j;
import org.javers.core.Javers;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 新增数据审计策略
 *
 * @author forest
 */
@Slf4j
@Component
public class CreateAuditStrategy implements AuditStrategy {

    @Resource
    private Javers javers;

    @Override
    public boolean supports(DataAudit dataAudit) {
        // 新增
        return ObjectUtil.equals(dataAudit.operationType(), OperationType.CREATE);
    }

    @Override
    public void execute(AuditContext context, Object result, DataAudit dataAudit, Object oldEntity) {
        try {
            Object newEntity = result;
            // 记录审计日志
            processChanges(context, newEntity, oldEntity, dataAudit);
        } catch (Exception e) {
            log.error("CREATE审计策略执行失败", e);
            context.getAuditLogService().recordAuditLog(
                    context, null, null, null, false, e.getMessage()
            );
        }
    }

}
